package com.example.ujsfish.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ujsfish.R;
import com.example.ujsfish.coord.CoordinateXY;
import com.example.ujsfish.model.ObstaclesPoint;
import com.example.ujsfish.model.monitor.Data;
import com.example.ujsfish.model.monitor.JsonRootBean;
import com.example.ujsfish.model.monitor.MonitorData;
import com.example.ujsfish.model.poolMap.PoolPoint;
import com.example.ujsfish.utils.AppNetService;
import com.example.ujsfish.model.ship.PoolName;
import com.example.ujsfish.utils.DeviceName;
import com.example.ujsfish.utils.RetrofitManager;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class CreateBoundaryByMan extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private static final String TAG = "CreateBoundaryByMan";
    RetrofitManager myRetrofitManager = RetrofitManager.getInstance();
    Retrofit myRetrofit = RetrofitManager.getRetrofit();
    AppNetService appNetService = myRetrofitManager.getApiService(AppNetService.class);

    Spinner spinner_poolName;


    Button btn_upload;
    Button btn_addPoint;
    EditText inputText_jingdu;
    EditText inputText_jweidu;
    EditText inputText_objectName;
    EditText inputText_show;
    Switch   aSwitch;
    boolean switchObject;  // false表示录入障碍物， true表示录入池塘边界

    //保存路径点
    private List<PoolPoint> objectList = new ArrayList<>();
    //路径点数量
    int pointCount;

    String originLat;
    String originLng;

    String id;
    String userName;



    List<String> poolList = new ArrayList();
    List<String> pathList = new ArrayList();

    String pool;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_boundary_by_man_activity);
        initView();
        id = DeviceName.getDeviceInstance().getDeviceId().get(0);
        aSwitch.setText(aSwitch.getTextOff());
        //从服务器获取原点经纬度
        getOriginPoint();
        //从服务器获取池塘编号
        getNewPoolData();
        //储存数据
        saveObject();

        //上传数据
        uploadObject();



    }

    private void uploadObject() {
        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (switchObject) { //上传边界
                    StringBuilder str = new StringBuilder();
                    for (PoolPoint poolPoint :
                            objectList) {
                        str.append(poolPoint.getPoint_X());
                        str.append(",");
                        str.append(poolPoint.getPoint_Y());
                        str.append(";");
                    }
                    if (inputText_objectName.getText() != null) {
                        Call<ResponseBody> addBoundary = appNetService.postAddBoundary(inputText_objectName.getText().toString(), "Boundary", str.toString(),userName);
                        addBoundary.enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                Toast.makeText(getApplication(),"添加池塘成功",Toast.LENGTH_SHORT).show();
                                //数据清除
                                objectList.clear();
                                pointCount = 0;

                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                Toast.makeText(getApplication(),"添加池塘失败",Toast.LENGTH_SHORT).show();
                                t.printStackTrace();
                            }
                        });


                    }

                } else {
                    StringBuilder str = new StringBuilder();
                    for (PoolPoint poolPoint :
                            objectList) {
                        str.append(poolPoint.getPoint_X());
                        str.append(",");
                        str.append(poolPoint.getPoint_Y());
                        str.append(";");
                    }

                    ObstaclesPoint obstaclesPoint = new ObstaclesPoint(inputText_objectName.getText().toString(),str.toString(),pool,inputText_objectName.getText().toString(),userName);
                    System.out.println(obstaclesPoint.toString());

                    Call<ResponseBody> responseBodyCall = appNetService.postAddObstacles(obstaclesPoint);
                    responseBodyCall.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            Toast.makeText(getApplication(),"添加障碍点成功",Toast.LENGTH_SHORT);
                            //数据清除
                            objectList.clear();
                            pointCount = 0;

                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {
                            Toast.makeText(getApplication(),"添加障碍点失败",Toast.LENGTH_SHORT);
                        }
                    });

                }
            }
        });



    }

    private void getOriginPoint() {
        Call<JsonRootBean> monitor = appNetService.postMonitor(id);
        monitor.enqueue(new Callback<JsonRootBean>() {
            @Override
            public void onResponse(Call<JsonRootBean> call, Response<JsonRootBean> response) {

                try {
                    JsonRootBean jsonRootBean = response.body();
                    Data monitorData = jsonRootBean.getData().get(0);
                    originLat = monitorData.getOrigin_latitude();
                    originLng = monitorData.getOrigin_longitude();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<JsonRootBean> call, Throwable t) {

            }
        });
    }

    private void saveObject() {
        btn_addPoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int count = pointCount + 1;
                String jin = inputText_jingdu.getText().toString();
                String wei = inputText_jweidu.getText().toString();
                CoordinateXY coordinateXY = new CoordinateXY(originLng,originLat);
                coordinateXY.getCoordinate(Double.parseDouble(jin),Double.parseDouble(wei));
                if ( machCoordinate(coordinateXY.getMovetoplaneENx()) && machCoordinate(coordinateXY.getMovetoplaneENy())) {
                    //将经纬度坐标转化为平面坐标
                    objectList.add(new PoolPoint(count,!switchObject,coordinateXY.getMovetoplaneENx(),coordinateXY.getMovetoplaneENy()));
                    pointCount++;
                } else {
                    Toast.makeText(getApplication(),"经纬度格式错误",Toast.LENGTH_SHORT).show();

                }




                showText();
            }
        });
    }
    private void showText() {
        StringBuilder stringBuilder = new StringBuilder();
        for (PoolPoint list: objectList) {
            stringBuilder.append(list.getPool_id() + "," + list.getPoint_X() + "," + list.getPoint_Y()+ ";")  ;
        }
        inputText_show.setText(stringBuilder);
        Log.d(TAG, "count :" + pointCount + "----- size :" + objectList.size());
    }





    private boolean machCoordinate(String pointString) {
        if (pointString.trim().length() != 6) {
            return false;
        }
        String pattern = "[SWEN]\\d\\d\\d\\.\\d";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(pointString);
        return m.matches();
    }

    private void initView() {
        inputText_jingdu = findViewById(R.id.inputText_jingdu);
        inputText_jweidu = findViewById(R.id.inputText_weidu);
        inputText_objectName = findViewById(R.id.text_objectName);
        inputText_show = findViewById(R.id.text_show);
        aSwitch = findViewById(R.id.switch1);
        btn_upload = findViewById(R.id.btn_upload);
        btn_addPoint = findViewById(R.id.btn_addPoint);

        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    switchObject = true;
                    aSwitch.setText(aSwitch.getTextOn());
                    spinner_poolName.setEnabled(false);


                }else {
                    switchObject = false;
                    aSwitch.setText(aSwitch.getTextOff());
                    spinner_poolName.setEnabled(true);

                }

                Log.d(TAG, "onCheckedChanged: " + isChecked);
                //数据清除
                objectList.clear();
                pointCount = 0;
            }
        });
    }




    private void getNewPoolData() {
        spinner_poolName = findViewById(R.id.spinner_poolName2);
        SharedPreferences preferences = getSharedPreferences("data",MODE_PRIVATE);
        userName = preferences.getString("userName", "");
        System.out.println("userName:::" + userName);
        Call<PoolName> responseBodyCall = appNetService.postFindPoolNameBU(userName);
        responseBodyCall.enqueue(new Callback<PoolName>() {
            @Override
            public void onResponse(Call<PoolName> call, Response<PoolName> response) {
                PoolName poolName = response.body();
                List<String> poolName_list = new ArrayList<>();
                //防止返回的数据中有空数据
                for (String data :
                        poolName.getData()) {
                    if (data != null){
                        poolName_list.add(data);
                    }
                }
                System.out.println("poolName" + poolName.getData().toString());
                initPoolSpinner(poolName_list, spinner_poolName);

            }

            @Override
            public void onFailure(Call<PoolName> call, Throwable t) {

            }
        });

    }

    private void initPoolSpinner(List<String> poolList, Spinner spinner_poolName) {
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, poolList);
        //设置样式
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner_poolName.setAdapter(arrayAdapter);
        //为Spinner设置选中事件监听器
        spinner_poolName.setOnItemSelectedListener(CreateBoundaryByMan.this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String data = parent.getItemAtPosition(position).toString();
        System.out.println("data" + data);
        TextView tv1;
        TextView tv2;

        switch (parent.getId()){
            case R.id.spinner_poolName2:
                 pool = data;
                 //从服务器获取路径名
                tv2 = (TextView)view;
                //tv2.setTextColor(getResources().getColor(R.color.colorBlack));
                break;
            default:break;
        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}